package com.luck.pf.security.user.web;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.luck.org.entity.SysDepartment;
import com.luck.org.entity.SysLog;
import com.luck.org.entity.SysRole;
import com.luck.org.entity.SysUser;
import com.luck.org.entity.VDepartment;
import com.luck.pf.common.Constants;
import com.luck.pf.common.entity.UserBean;
import com.luck.pf.framework.action.BaseActionSupport;
import com.luck.pf.security.dept.logic.IDeptLogic;
import com.luck.pf.security.dept.qry.DeptQry;
import com.luck.pf.security.role.logic.IRoleLogic;
import com.luck.pf.security.role.qry.RoleQry;
import com.luck.pf.security.user.logic.IUserLogic;
import com.luck.pf.security.user.qry.UserQry;
import com.luck.pf.util.DateUtil;
import com.luck.pf.util.Md5Key;
import com.luck.pf.util.ObjectUtil;
import com.luck.pf.util.Page;

/**
 * 说明:
 * Copyright: Copyright (c) 2010
 * @author zhangwr 2011-8-11 上午09:40:33
 * @version 1.0
 */
public class UserAction extends BaseActionSupport {
	private static final long serialVersionUID = 3934824067479600714L;
	IDeptLogic deptLogic;
	IUserLogic userLogic;
	IRoleLogic roleLogic;
	UserQry qry;
	DeptQry deptQry;
	RoleQry roleQry;
	SysUser entity;
	List<SysUser> users;
	List<SysDepartment> depts;
	List<SysRole> allRoles,userRoles;
	Page page;
	Long[] roleIds;
	public String index() throws Exception{
		return "index";
	}
	public String tree() throws Exception{
		UserBean userBean = super.getUserInfo();
		if (StringUtils.isNotBlank(super.qryHex)) {
			deptQry = (DeptQry)ObjectUtil.getObjectFromHex(qryHex);
		}
		if (deptQry == null) {
			deptQry = new DeptQry();
		}
		deptQry.setUserInfo(userBean);
		depts = deptLogic.findDepts(deptQry);
		super.title="机构树";
		return "tree";
	}
	/**
	 * 根据用户得到角色
	 * @return
	 * @throws Exception
	 */
	public String roles() throws Exception{
		entity = userLogic.get(SysUser.class, entity.getId());
		UserBean userBean = super.getUserInfo();
		if (StringUtils.isNotBlank(super.qryHex)) {
			roleQry = (RoleQry)ObjectUtil.getObjectFromHex(qryHex);
		}
		if (roleQry == null) {
			roleQry = new RoleQry();
		}
		roleQry.setUserInfo(userBean);
		allRoles = roleLogic.findRoles(roleQry);
		userRoles = new ArrayList<SysRole>(entity.getRoles());
		super.title="设置角色";
		return "userRole";
	}
	/**
	 * 根据传入的角色列表，授权给此用户
	 * @throws Exception
	 */
	public String addRole() throws Exception{
		entity = userLogic.get(SysUser.class, entity.getId());
		UserBean userBean = super.getUserInfo();
		if (StringUtils.isNotBlank(super.qryHex)) {
			roleQry = (RoleQry)ObjectUtil.getObjectFromHex(qryHex);
		}
		if (roleQry == null) {
			roleQry = new RoleQry();
		}
		roleQry.setUserInfo(userBean);
		roleQry.setRoleIds(roleIds);
		entity.setRoles(new HashSet(roleLogic.findRoles(roleQry)));
		try {
			userLogic.save(entity);
			super.renderJsonSuccess("保存成功");
		} catch (Exception e) {
			super.renderJsonError("保存失败");
		}
		return null;
	}
	public String list() throws Exception{
		UserBean userBean = super.getUserInfo();
		if (StringUtils.isNotBlank(super.qryHex)) {
			qry = (UserQry)ObjectUtil.getObjectFromHex(qryHex);
		}
		if (qry == null) {
			qry = new UserQry();
		}
		if(qry.getDeptId()!=null&&StringUtils.isBlank(qry.getDeptName())){
			qry.setDeptName(userLogic.get(VDepartment.class, qry.getDeptId()).getDeptName());
		}
		qry.setUserInfo(userBean);
		page = userLogic.findUserPage(qry);
		super.title="用户列表";
		return "list";
	}

	public String checkUser() throws Exception {	
		boolean isCorrect = userLogic.checkUser(entity);
		super.rendText(String.valueOf(isCorrect));
		return null;
	}
	public String toAdd() throws Exception{
		entity = new SysUser();
		entity.setId(ADD_PK);
		if(qry!=null&& qry.getDeptId()!=null){
			SysDepartment dept = userLogic.get(SysDepartment.class, qry.getDeptId());
			if(dept != null){
				qry.setDeptId(dept.getId());
				qry.setDeptName(dept.getDeptName());
				entity.setDept(dept);
				entity.setDeptId(dept.getId());
				}
		}
		super.title="增加用户";
		return "edit";
	}
	public String toEdit() throws Exception{
		entity = userLogic.get(SysUser.class, entity.getId());
		if(qry == null)
			qry = new UserQry();
		qry.setDeptId(entity.getDeptId());
		qry.setDeptName(entity.getDept().getDeptName());
		super.title="修改用户";
		return "edit";
	}
	public String edit() throws Exception{
		UserBean userBean = super.getUserInfo();
		SysUser user = userLogic.findUserByLoginname(entity.getLoginname());
		if(user != null && entity.getId()==ADD_PK){
			super.renderJsonError("此登陆名已存在");
			return null;
		}
		//entity = userLogic.get(SysUser.class, entity.getId());
		entity.setCreatedDate(DateUtil.getDate());
		entity.setCreatedUser(userBean.getUserId());
		entity.setOperTime(DateUtil.getDate());
		entity.setOperUser(userBean.getUserId());
		if(entity.getId() == ADD_PK){//新增
			entity.setPassword(Md5Key.MD5(Constants.INIT_PASSWORD));
			entity.setPsw(Constants.INIT_PASSWORD);
			entity.setId(null);
			userLogic.saveUser(entity);
		}else{//修改
			super.copyProperties(user, entity);
			userLogic.saveUser(user);			
		}
		super.renderJsonSuccess("保存成功");
		return null;
	}
	public String checkLoginname() throws Exception {
		SysUser user = userLogic.findUserByLoginname(entity.getLoginname());
		if(user != null && entity.getId()!=ADD_PK)
			super.renderJsonSuccess(String.valueOf(false));
		else
			super.renderJsonSuccess(String.valueOf(true));
		return null;
	}
	public String changeStatus() throws Exception{
		UserBean userBean = super.getUserInfo();
		entity = userLogic.get(SysUser.class, entity.getId());
		String str = userLogic.saveUserStatus(userBean,entity);
		if(StringUtils.isNotBlank(str))
			super.renderJsonError(str);
		else
			super.renderJsonSuccess("操作成功 ");
		return null;
	}
	public String delete() throws Exception{
		UserBean userBean = super.getUserInfo();
		entity = userLogic.get(SysUser.class, entity.getId());
		String str = "";
		try {
			str = userLogic.deleteUser(entity, userBean, createLog(userBean, "删除用户["+entity.getLoginname()+"]", "2"));
		} catch (Exception e) {
			str = e.getMessage();
		}
		if(StringUtils.isNotBlank(str))
			super.renderJsonError(str+"不能删除");
		else
			super.renderJsonSuccess(str);
		return null;
	}
	public String view() throws Exception{
		entity = userLogic.get(SysUser.class, entity.getId());
		return "view";
	}
	public String editPw() throws Exception{
		entity = userLogic.findUserByLoginname(getUserInfo().getLoginName());
		String oldPassword = super.getStringParameter("oldPassword", false);
		String password = super.getStringParameter("password", false);
		if(!entity.getPassword().equals(Md5Key.MD5(oldPassword))){
			super.renderJsonError("旧密码不正确！");
		}else{
			entity.setPsw(password);
			entity.setPassword(Md5Key.MD5(password));
			userLogic.save(entity);
			super.renderJsonSuccess("修改成功");			
		}
		return null;
	}
	
	/**
	 * 初始化用户密码
	 * @return
	 * @throws Exception
	 */
	public String toEditPwInit() throws Exception{
		return "editPwInit";
	}
	public String editPwInit() throws Exception{
		String loginname = super.getStringParameter("loginname", false);
		entity = userLogic.findUserByLoginname(loginname);
		StringBuffer bf = new StringBuffer();
		if(entity == null)
			bf.append("没有此登陆名！<br/>");
		else if(getUserInfo().getDeptId() !=1L){//如果不为顶级机构
			if(!entity.getDeptId().equals(getUserInfo().getDeptId()))
				bf.append("只能重置您同一机构的用户密码！<br/>");
		}
		
		if(StringUtils.isNotBlank(bf.toString())){
			super.renderJsonError(bf.toString());
		}else{
			entity.setPsw(Constants.INIT_PASSWORD);
			entity.setPassword(Md5Key.MD5(Constants.INIT_PASSWORD));
			userLogic.save(entity);
			SysLog log = createLog(getUserInfo(), "重置用户["+entity.getLoginname()+"]密码", "2");
			userLogic.save(log);
			super.renderJsonSuccess("重置成功,新密码为:["+Constants.INIT_PASSWORD+"]");			
		}
		return null;
	}
	public IUserLogic getUserLogic() {
		return userLogic;
	}
	public void setUserLogic(IUserLogic userLogic) {
		this.userLogic = userLogic;
	}
	public UserQry getQry() {
		return qry;
	}
	public void setQry(UserQry qry) {
		this.qry = qry;
	}
	public List<SysUser> getUsers() {
		return users;
	}
	public void setUsers(List<SysUser> users) {
		this.users = users;
	}
	public SysUser getEntity() {
		return entity;
	}
	public void setEntity(SysUser entity) {
		this.entity = entity;
	}
	public IDeptLogic getDeptLogic() {
		return deptLogic;
	}
	public void setDeptLogic(IDeptLogic deptLogic) {
		this.deptLogic = deptLogic;
	}
	public DeptQry getDeptQry() {
		return deptQry;
	}
	public void setDeptQry(DeptQry deptQry) {
		this.deptQry = deptQry;
	}
	public List<SysDepartment> getDepts() {
		return depts;
	}
	public void setDepts(List<SysDepartment> depts) {
		this.depts = depts;
	}
	public Page getPage() {
		return page;
	}
	public void setPage(Page page) {
		this.page = page;
	}
	public IRoleLogic getRoleLogic() {
		return roleLogic;
	}
	public void setRoleLogic(IRoleLogic roleLogic) {
		this.roleLogic = roleLogic;
	}
	public RoleQry getRoleQry() {
		return roleQry;
	}
	public void setRoleQry(RoleQry roleQry) {
		this.roleQry = roleQry;
	}
	public List<SysRole> getAllRoles() {
		return allRoles;
	}
	public void setAllRoles(List<SysRole> allRoles) {
		this.allRoles = allRoles;
	}
	public List<SysRole> getUserRoles() {
		return userRoles;
	}
	public void setUserRoles(List<SysRole> userRoles) {
		this.userRoles = userRoles;
	}
	public Long[] getRoleIds() {
		return roleIds;
	}
	public void setRoleIds(Long[] roleIds) {
		this.roleIds = roleIds;
	}
}
